package com.coincalf.task.entity;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.joda.time.DateTime;

import java.math.BigDecimal;

/**
 * @author qiang
 */
public class PricesConvert {

    public static Prices convert(JsonObject object) {
        JsonObject pairs = object.getAsJsonArray("pairs").get(0).getAsJsonObject();
        long updated = pairs.get("Updated").getAsLong();
        String symbol = pairs.get("Symbol").getAsString();
        JsonArray rates = pairs.getAsJsonArray("Rates");
        BigDecimal bid = rates.get(0).getAsBigDecimal();
        BigDecimal ask = rates.get(1).getAsBigDecimal();
        BigDecimal high = rates.get(2).getAsBigDecimal();
        BigDecimal low = rates.get(3).getAsBigDecimal();

        return new Prices()
                .setUpdated(updated)
                .setAsk(ask)
                .setBid(bid)
                .setHigh(high)
                .setLow(low)
                .setSymbol(symbol);
    }

    public static String convertKline(Kline kline) {
        JSONArray array = new JSONArray();
        array.add(kline.getUpdated());
        array.add(kline.getOpen());
        array.add(kline.getHigh());
        array.add(kline.getLow());
        array.add(kline.getClose());
        array.add(0);
        return array.toJSONString();
    }

    public static Kline format(Prices prices) {
        return new Kline()
                .setSymbol(prices.getSymbol())
                .setUpdated(new DateTime(prices.getUpdated()).getMillis())
                .setOpen(prices.getPrice())
                .setHigh(prices.getPrice())
                .setClose(prices.getPrice())
                .setLow(prices.getPrice());
    }

    public static Kline formatKline(String json) {
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(json).getAsJsonArray();
        long updated = jsonArray.get(0).getAsLong();
        BigDecimal open = jsonArray.get(1).getAsBigDecimal();
        BigDecimal high = jsonArray.get(2).getAsBigDecimal();
        BigDecimal low = jsonArray.get(3).getAsBigDecimal();
        BigDecimal close = jsonArray.get(4).getAsBigDecimal();
        return new Kline()
                .setUpdated(updated)
                .setOpen(open)
                .setHigh(high)
                .setLow(low)
                .setClose(close);
    }
}
